import 'package:get/get.dart';
import 'package:flutter/material.dart';

import '../../../domain/services/device_business.dart';
import '../../../data/models/device_model.dart';
import '../../../constants/enums/app_status.dart';
import '../../../routes/app_routes.dart';

/// 设备列表控制器
class DeviceListController extends GetxController {
  // 注入设备业务服务
  final DeviceBusiness _deviceBusiness = Get.find<DeviceBusiness>();

  // 设备列表
  final RxList<DeviceModel> devices = <DeviceModel>[].obs;
  
  // 加载状态
  final Rx<AppStatus> status = AppStatus.loading.obs;
  
  // 分页信息
  int _currentPage = 1;
  final int _limit = 15; // 每页加载数量
  final RxBool _hasMoreData = true.obs;
  bool get hasMoreData => _hasMoreData.value;
  
  // 搜索控制器
  final TextEditingController searchController = TextEditingController();
  String? _currentSearchQuery;
  
  // 筛选条件 (示例)
  final RxString? filterStatus = RxString(null);
  final RxString? filterType = RxString(null);

  @override
  void onInit() {
    super.onInit();
    fetchDevices(); // 初始加载
    // 监听搜索框变化，延迟执行搜索以避免频繁请求
    debounce(searchController.obs.value.text, (_) => searchDevices(), time: const Duration(milliseconds: 500));
  }

  @override
  void onClose() {
    searchController.dispose();
    super.onClose();
  }

  /// 获取设备列表
  Future<void> fetchDevices({bool isLoadMore = false}) async {
    if (status.value == AppStatus.loadingMore && isLoadMore) return; // 防止重复加载更多
    if (!isLoadMore) {
      status.value = AppStatus.loading;
      _currentPage = 1;
      _hasMoreData.value = true; // 重置分页状态
      devices.clear(); // 清空旧数据
    } else {
      status.value = AppStatus.loadingMore;
    }

    try {
      // 构建筛选参数
      final filters = <String, dynamic>{};
      if (_currentSearchQuery != null && _currentSearchQuery!.isNotEmpty) {
        filters['search'] = _currentSearchQuery;
      }
      if (filterStatus?.value != null) {
        filters['status'] = filterStatus!.value;
      }
      if (filterType?.value != null) {
        filters['type'] = filterType!.value;
      }
      
      final fetchedDevices = await _deviceBusiness.fetchDeviceList(
        page: _currentPage,
        limit: _limit,
        filters: filters.isNotEmpty ? filters : null,
      );

      if (fetchedDevices.isEmpty || fetchedDevices.length < _limit) {
        _hasMoreData.value = false; // 没有更多数据了
      }

      if (isLoadMore) {
        devices.addAll(fetchedDevices);
      } else {
        devices.assignAll(fetchedDevices);
      }
      
      if (devices.isEmpty) {
         status.value = AppStatus.empty;
      } else {
         status.value = AppStatus.success;
      }
      
      _currentPage++; // 准备加载下一页
      
    } catch (e) {
      print('加载设备列表失败: $e');
      status.value = AppStatus.error;
      // 可以设置错误消息
    }
  }
  
  /// 刷新设备列表
  Future<void> refreshDevices() async {
    await fetchDevices();
  }

  /// 加载更多设备
  Future<void> loadMoreDevices() async {
    if (_hasMoreData.value && status.value != AppStatus.loadingMore) {
       await fetchDevices(isLoadMore: true);
    }
  }
  
  /// 搜索设备
  void searchDevices() {
     _currentSearchQuery = searchController.text.trim();
     refreshDevices(); // 重新加载数据
  }
  
  /// 应用筛选
  void applyFilters() {
     refreshDevices(); // 重新加载数据
  }
  
  /// 清除筛选
  void clearFilters() {
    filterStatus?.value = null;
    filterType?.value = null;
    refreshDevices();
  }

  /// 导航到设备详情页面
  void navigateToDeviceDetail(String deviceId) {
    Get.toNamed('${AppRoutes.DEVICE_DETAIL}/$deviceId'); // 假设路由是 /device/detail/:id
  }

  /// 导航到添加设备页面
  void navigateToAddDevice() {
    Get.toNamed(AppRoutes.DEVICE_ADD);
  }
} 